/**
 * 单向链表实现栈
 */

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    struct Node *next; // 栈顶指针
    int data;          // 元素的值
} Node;

typedef struct Stack {
    Node *top;
} Stack;

Stack *initStack() {
    Stack *stack = (Stack *)malloc(sizeof(Stack));
    if (stack == NULL) {
        perror("Failed to located memory!");
        exit(EXIT_FAILURE);
    }
    stack->top = NULL;
    return stack;
}

bool isEmpty(Stack *stack) { return stack->top == NULL; }

void push(Stack *stack, int data) {
    Node *node = (Node *)malloc(sizeof(Node));
    if (node == NULL) {
        perror("Failed to located memory!");
        exit(EXIT_FAILURE);
    }
    node->data = data;
    node->next = stack->top; // 新节点指向原栈顶节点
    stack->top = node;       // 更新当前栈顶节点
    printf("%d入栈\n", data);
}

int pop(Stack *stack) {
    if (isEmpty(stack)) {
        printf("Stack is empty");
        exit(EXIT_FAILURE);
    }
    Node *temp = stack->top; // 获取栈顶节点
    int result = temp->data;
    stack->top = stack->top->next; // 更新栈顶指针
    free(temp);                    // 释放栈顶节点
    return result;
}

void printStack(Stack *stack) {
    printf("打印栈：\n");
    Node *current = stack->top;
    while (current != NULL) {
        printf("%d\n", current->data);
        current = current->next;
    }
}

void destroyStack(Stack *stack) {
    while (stack->top != NULL) {
        Node *temp = stack->top;
        stack->top = stack->top->next;
        free(temp);
    }
    free(stack);
}

int main() {
    Stack *stack = initStack();
    push(stack, 1);
    push(stack, 2);
    push(stack, 3);
    push(stack, 4);
    push(stack, 5);
    push(stack, 6);
    push(stack, 7);
    push(stack, 8);
    push(stack, 9);
    push(stack, 10);
    printStack(stack);
    printf("%d出栈\n", pop(stack));
    printf("%d出栈\n", pop(stack));
    printf("%d出栈\n", pop(stack));
    printf("%d出栈\n", pop(stack));
    printf("%d出栈\n", pop(stack));
    printf("%d出栈\n", pop(stack));
    printf("%d出栈\n", pop(stack));
    printf("%d出栈\n", pop(stack));
    printf("%d出栈\n", pop(stack));
    printf("%d出栈\n", pop(stack));
    printStack(stack);
    destroyStack(stack);
}